package com.easou.sdk.controller;

import java.lang.reflect.Method;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.json.MappingJacksonJsonView;

import com.easou.sdk.model.UserToken;
import com.easou.sdk.partner.QiHooSdk;
import com.easou.sdk.service.PartnerService;
import com.easou.sdk.service.PartnerServiceFactory;
import com.easou.sdk.service.ServiceReturnCode;
import com.easou.sdk.service.WebApiService;
import com.easou.sdk.service.exception.ServiceException;
import com.easou.sdk.utils.EncryptUtil;
import com.easou.sdk.utils.config.Config;
import com.easou.sdk.utils.json.Json;

@Controller
public class LoginController {

	private static Logger LOG = Logger.getLogger(LoginController.class);

	@Autowired
	private PartnerServiceFactory serviceFactory;

	@RequestMapping("/webApi/login.do")
	public ModelAndView login(HttpServletRequest req, HttpServletResponse res) {
		String token = req.getParameter("token");
		String partnerId = req.getParameter("partnerId");
		String serverId = req.getParameter("serverId");
		String timestamp = req.getParameter("timestamp");
		String sign = req.getParameter("sign");
		String imei = req.getParameter("fr");
		String mac = req.getParameter("mac");
		String idfa = req.getParameter("idfa");

		PartnerService ps = serviceFactory.getBean(partnerId);
		Map<String, Object> map = new HashMap<String, Object>();
		try {

			Map<String, String> params = new HashMap<String, String>();
			params.put("imei", imei);
			params.put("mac", mac);
			params.put("idfa", idfa);

			UserToken userToken = ps.login(token, partnerId, serverId, Long.parseLong(timestamp), sign, params);
			if (userToken != null) {
				map.put("rc", WebApiService.SUCCESS);
//				Map<String, String> data = new HashMap<String, String>();
//				data.put("tk", userToken.getToken());
//				data.put("uid", userToken.getUserId());
//				data.put("puid", userToken.getPartnerUserId());
//				data.put("ptk", userToken.getPartnerToken());
//				data.put("exti", userToken.getExtInfo());
//				Notice notice = webApiService.getNotice(serverId, partnerId);
//				if (notice != null && notice.getIsEnable() == 1) {
//					data.put("title", notice.getTitle());
//					data.put("notice", notice.getContent());
//				} else {
//					notice = webApiService.getNotice(serverId, "all");
//					if (notice != null && notice.getIsEnable() == 1) {
//						data.put("title", notice.getTitle());
//						data.put("notice", notice.getContent());
//					}
//				}
//				map.put("dt", data);
			} else {
				map.put("rc", WebApiService.UNKNOWN_ERROR);
			}
		} catch (ServiceException e) {
			LOG.error(e.getMessage(), e);
			map.put("rc", e.getCode());
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
			map.put("rc", WebApiService.UNKNOWN_ERROR);
		}
		ModelAndView modelView = new ModelAndView();
		MappingJacksonJsonView view = new MappingJacksonJsonView();
		view.setAttributesMap(map);
		modelView.setView(view);
		LOG.debug("parnterId:" + partnerId + "," + Json.toJson(map));
		return modelView;
	}

	@RequestMapping("/webApi/getSysTime.do")
	public ModelAndView getSysTime() {
		Map<String, Object> map = new HashMap<String, Object>();
		Map<String, Long> tMap = new HashMap<String, Long>();
		tMap.put("t", System.currentTimeMillis());
		map.put("rc", 1000);
		map.put("dt", tMap);
		ModelAndView modelView = new ModelAndView();
		MappingJacksonJsonView view = new MappingJacksonJsonView();
		view.setAttributesMap(map);
		modelView.setView(view);
		return modelView;
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	@RequestMapping("/webApi/updateConfigs.do")
	public ModelAndView updateServers() {
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			Properties properties = new Properties();
			properties.load(QiHooSdk.class.getResourceAsStream("/sdk.properties"));
			Iterator<Entry<Object,Object>> iterator = properties.entrySet().iterator();
			Set<String> set = new HashSet<String>();
			while (iterator.hasNext()) {
				try {
					Entry<Object,Object> entry = iterator.next();
					String className = StringUtils.split(entry.getKey().toString(),".")[0];
					if(!set.contains(className)){
						Class sdkClass = Class.forName("com.lodogame.ldsg.partner.sdk."+className);
						if(sdkClass == null){
							continue;
						}
						Method instanceMethod = sdkClass.getMethod("instance",new Class[]{});
						Method reloadMethod = sdkClass.getMethod("reload",new Class[]{});
						Object object = instanceMethod.invoke(null,null);
						reloadMethod.invoke(object,null);
						LOG.info(className+" reload!");
						set.add(className);
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
//		QiHooSdk.instance().reload();
//		BaiduSdk.instance().reload();
//		UcSdk.instance().reload();
//		LenovoSdk.instance().reload();
//		EasouSdk.instance().reload();
//		PartnerConfig.ins().reload();
//		BaiduZsSdk.instance().reload();
//		AnZhiSdk.instance().reload();
//		AppChinaSdk.instance().reload();
//		AppleSdk.instance().reload();
//		ChangWanSdk.instance().reload();
//		ChinaMobileSdk.instance().reload();
//		DangleSdk.instance().reload();
//		DuokuSdk.instance().reload();
//		HucnSdk.instance().reload();
//		SanqiWanwanSdk.instance().reload();
//		ShiJiaSdk.instance().reload();
//		XiaomiSdk.instance().reload();
//		KuaiBoSdk.instance().reload();
//		AnZhiAdSdk.instance().reload();
//		PPSSdk.instance().reload();
//		KuWoSdk.instance().reload();
		map.put("rc", 1000);
		ModelAndView modelView = new ModelAndView();
		MappingJacksonJsonView view = new MappingJacksonJsonView();
		view.setAttributesMap(map);
		modelView.setView(view);
		return modelView;
	}

	private void checkSign(String item, String playerIds, long timestamp, String sign) {
		long now = System.currentTimeMillis();
		if ((now - timestamp) > 1000 * 60) {
			LOG.info("请求时间超出范围：" + timestamp + "(" + new Date(timestamp) + ")");
			throw new ServiceException(ServiceReturnCode.SIGN_CHECK_ERROR, "请求时间超出范围（10s）");
		}
		String md5 = EncryptUtil.getMD5(item + playerIds + timestamp + Config.ins().getSignKey());
		if (!md5.toLowerCase().equals(sign.toLowerCase())) {
			LOG.info("请求签名不正确：" + sign + "(" + md5 + ")");
			throw new ServiceException(ServiceReturnCode.SIGN_CHECK_ERROR, "请求签名不正确");
		}
	}


}
